<?php
/**********************功能性工具******************************/
/**
 * @Desc     用于判断为空为空字符串判断
 * @Author   pekey
 * @DateTime 2020-05-12T19:25:18+0800
 * @param    [type] 对象参数
 * @return   boolean
 */
function isEmpty($s)
{
    if ($s == null || $s == "") {
        return true;
    }

    return false;
}

/**
 * @Desc     返回值-Controller返回页面去
 * @Author   pekey
 * @DateTime 2020-05-12T19:25:48+0800
 * @param    errorCode,错误代码枚举，包含错误代码，及错误信息
 * @param    boolean，返回是否正确
 * @param    array，数据
 * @param    array，其他数据
 * @return   [type]，返回json类型
 */
function retJson($errorCode, $data = array(), $append = array())
{
    $ret = array();

    $ret[RET_CODE]   = $errorCode[TPEnum::Value];
    $ret[RET_MSG]    = $errorCode[TPEnum::Caption];
    $ret[RET_EN_MSG] = $errorCode[TPEnum::Append1];
    $ret[RET_STATUS] = checkRetStatus($errorCode);

    if (is_array($data)) {
        $ret[RET_DATA] = json_encode($data);
    } else {
        $ret[RET_DATA] = $data;
    }
    if (is_array($append)) {
        $ret[RET_APPEND] = json_encode($append);
    } else {
        $ret[RET_APPEND] = $append;
    }

    return json_encode($ret);
}

/**
 * @Desc     返回值-Service返回Controller
 * @Author   pekey
 * @DateTime 2020-05-12T19:25:48+0800
 * @param    string,返回信息
 * @param    boolean，返回是否正确
 * @param    array，数据
 * @param    array，其他数据
 * @return   [type]，返回json类型
 */
function retArray($errorCode, $data = array(), $append = array())
{
    $ret = array();

    $ret[RET_CODE]   = $errorCode[TPEnum::Value];
    $ret[RET_MSG]    = $errorCode[TPEnum::Caption];
    $ret[RET_EN_MSG] = $errorCode[TPEnum::Append1];
    $ret[RET_STATUS] = checkRetStatus($errorCode);
    $ret[RET_DATA]   = $data;
    $ret[RET_APPEND] = $append;

    return $ret;
}

/**
 * [checkRetStatus 通过errcode判断是否属于成功]
 * @Description 通过errcode判断是否属于成功
 * @Author      FengPQ
 * @DateTime    2020-05-15T00:06:13+0800
 * @param       [type]                   $errorCode [错误代码]
 * @return      [type]                              [布尔类型]
 */
function checkRetStatus($errorCode)
{
    if ($errorCode == ErrCode::ErrCode_00000) {
        return true;
    }
    return false;
}

/**
 * @Desc     retArray转retJson
 * @Author   pekey
 * @DateTime 2020-05-12T19:26:54+0800
 * @param    [type]
 * @return   [type]
 */
function toRetJson($retArray)
{
    $errorCode = (new ErrCode)->show($retArray[RET_CODE]);
    return retJson($errorCode, $retArray[RET_DATA], $retArray[RET_APPEND]);
}

/**
 * @Desc     字符串formatter
 * @Author   pekey
 * @DateTime 2020-05-12T19:27:03+0800
 * @return   [type]
 * ex:
 *     $v = str_format("aaa{0}...{1}",$a,$b);
 */
function str_format()
{
    $args = func_get_args();
    if (count($args) == 0) {return;}
    if (count($args) == 1) {return $args[0];}
    $str = array_shift($args);
    $match=function ($match) use ($args){
        return isset($args[$match[1]]) ? $args[$match[1]] : $match[0];
    };
    $str = preg_replace_callback('/\\{(0|[1-9]\\d*)\\}/', $match, $str);
    return $str;
}

/**
 * @Desc     SQL 字符串格式化，带SQL注入问题
 * @Author   pekey
 * @DateTime 2020-05-12T19:27:56+0800
 * @return   [type]
 * ex:
 *     $v = sql_format("aaa{0}...{1}",$a,$b);
 */
function sql_format()
{
    $CI   = &get_instance();
    $args = func_get_args();
    if (count($args) == 0) {return;}
    if (count($args) == 1) {return $args[0];}
    $str = array_shift($args);
    $match=function ($match) use ($args){
        return isset($args[$match[1]]) ? $args[$match[1]] : $match[0];
    };
    $str = preg_replace_callback('/\\{(0|[1-9]\\d*)\\}/', $match, $CI->db->escape($str));
    return $str;
}

/**
 * @Desc     like类型SQL 字符串格式化，带SQL注入问题
 * @Author   pekey
 * @DateTime 2020-05-12T19:28:39+0800
 * @return   [type]
 * ex:
 *     $v = sql_like_format("aaa{0}...{1}",$a,$b);
 */
function sql_like_format()
{
    $CI   = &get_instance();
    $args = func_get_args();
    if (count($args) == 0) {return;}
    if (count($args) == 1) {return $args[0];}
    $str = array_shift($args);
    $match=function ($match) use ($args){
        return isset($args[$match[1]]) ? $args[$match[1]] : $match[0];
    };
    $str = preg_replace_callback('/\\{(0|[1-9]\\d*)\\}/', $match, $str);
    return $str;
}

/**
 * [array_sql_in 对数组进行in拼接]
 * @Description 对数组进行in拼接
 * @Author      FengPQ
 * @DateTime    2020-05-14T09:05:34+0800
 * @param       [type]                   $v [数组对象]
 * @return      [type]                      [带，的拼接结果]
 */
function array_sql_in($v)
{
    if (is_array($v) && count($v) != 0) {
        return "'" . str_replace(",", "','", join(",", $v)) . "'";
    } else if (is_array($v)) {
        return $v[0];
    }
    return $v;

}

/**
 * @Desc     随机生成16位唯一编号
 * @Author   pekey
 * @DateTime 2020-05-12T19:29:04+0800
 * @return   [type]
 */
function buildSID()
{
    // return date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    $trade_no = substr(date('Y'), 3, 1) . time() . rand(100, 999) . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 5, 13), 1))), 9, 2);
    return $trade_no;
}

/**
 * @Desc     二维数组去重
 * @Author   pekey
 * @DateTime 2020-05-12T19:29:20+0800
 * @param    array
 * @return   [type]
 */
function more_array_unique($arr = array())
{
    foreach ($arr[0] as $k => $v) {
        $arr_inner_key[] = $k; //先把二维数组中的内层数组的键值记录在在一维数组中
    }
    foreach ($arr as $k => $v) {
        $v        = join(",", $v); //降维 用implode()也行
        $temp[$k] = $v; //保留原来的键值 $temp[]即为不保留原来键值
    }
    // printf("After split the array:<br>");
    // print_r($temp);    //输出拆分后的数组
    // echo"<br/>";
    $temp = array_unique($temp); //去重：去掉重复的字符串
    foreach ($temp as $k => $v) {
        $a             = explode(",", $v); //拆分后的重组 如：Array( [0] => james [1] => 30 )
        $arr_after[$k] = array_combine($arr_inner_key, $a); //将原来的键与值重新合并
    }
    //ksort($arr_after);//排序如需要：ksort对数组进行排序(保留原键值key) ,sort为不保留key值
    return $arr_after;
}

/**
 * [msectime description]
 * @Description 获取毫秒
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:37:28+0800
 * @return      [type]                   [description]
 */
function msectime()
{
    $now       = microtime();
    $now_array = explode(' ', $now);
    $hao       = $now_array['0'];
    return $hao;
}

/**
 * [listToTree description]
 * @Description 根据pid无线级分类转化成树状多维数组
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:37:38+0800
 * @param       [type]                   $list  [数据列]
 * @param       string                   $pk    [description]
 * @param       string                   $pid   [description]
 * @param       string                   $child [description]
 * @param       integer                  $root  [description]
 * @return      [type]                          [description]
 */
function listToTree($list, $pk = 'id', $pid = 'pid', $child = '_child', $root = 0)
{
    $tree = array(); // 创建Tree
    if (is_array($list)) {
        // 创建基于主键的数组引用
        $refer = array();
        foreach ($list as $key => $data) {
            $refer[$data[$pk]] = &$list[$key];
        }

        foreach ($list as $key => $data) {
            // 判断是否存在parent
            $parentId = $data[$pid];
            if ($root == $parentId) {
                $tree[$data[$pk]] = &$list[$key];
            } else {
                if (isset($refer[$parentId])) {
                    $parent           = &$refer[$parentId];
                    $parent[$child][] = &$list[$key];
                }
            }
        }
    }
    return $tree;
}

/**
 * [cacheArray description]
 * @Description 数组存入text文件做为缓存
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:38:10+0800
 * @param       [type]                   $array    [description]
 * @param       [type]                   $filename [description]
 * @return      [type]                             [description]
 */
function cacheArray($array, $filename)
{
    $filename  = $filename;
    $file_hwnd = fopen($filename, "w");
    fwrite($file_hwnd, serialize($array)); //输入序列化的数据
    fclose($file_hwnd);
}

/**
 * [unCacheArray description]
 * @Description 从text文件中取出缓存还原成数组
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:38:20+0800
 * @param       [type]                   $filename [description]
 * @return      [type]                             [description]
 */
function unCacheArray($filename)
{
    $filename  = $filename;
    $file_hwnd = fopen($filename, "r");
    $content   = fread($file_hwnd, filesize($filename)); // 读去文件全部内容
    fclose($file_hwnd);
    $array_2 = unserialize($content); // 将文本数据转换回数组
    return $array_2;
}

/**
 * [getPasswrodWithTwiceEncode description]
 * @Description 二次加盐
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:38:30+0800
 * @param       [type]                   $password [密码]
 * @param       [type]                   $salt     [盐]
 * @return      [type]                             [加密后的密码]
 */
function getPasswrodWithTwiceEncode($password, $salt)
{
    $encryptedPassword         = md5($password);
    $encryptedWithSaltPassword = md5($encryptedPassword . $salt);
    return $encryptedWithSaltPassword;
}

/**
 * [getRandNum description]
 * @Description 随机获取Num
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:38:57+0800
 * @param       integer                  $length [description]
 * @return      [type]                           [description]
 */
function getRandNum($length = 8)
{
    // 密码字符集，可任意添加你需要的字符
    $chars = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

    // 在 $chars 中随机取 $length 个数组元素键名
    $keys     = array_rand($chars, $length);
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        // 将 $length 个数组元素连接成字符串
        $password .= $chars[$keys[$i]];
    }
    return $password;
}

/**
 * [getRandStr description]
 * @Description 随机获取
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:39:08+0800
 * @param       integer                  $length [字符串长度]
 * @return      [type]                           [description]
 */
function getRandStr($length = 8)
{
    // 密码字符集，可任意添加你需要的字符
    $chars = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
        'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's',
        't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
        'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
        'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9');

    // 在 $chars 中随机取 $length 个数组元素键名
    $keys     = array_rand($chars, $length);
    $password = '';
    for ($i = 0; $i < $length; $i++) {
        // 将 $length 个数组元素连接成字符串
        $password .= $chars[$keys[$i]];
    }
    return $password;
}

//手机短信
function sendMessage($destination, $text)
{

}

/**
 * [checkStringIsBase64 description]
 * @Description 判断是否是base64图片
 * @Author      FengPQ
 * @DateTime    2020-05-14T08:39:39+0800
 * @param       [type]                   $str [图片地址]
 * @return      [type]                        [description]
 */
function checkStringIsBase64($str)
{
    if (strpos($str, 'data:image') === 0) {
        return true;
    }
    return false;
}

/**
 * [sys_get_client_ip 获取客户端IP地址]
 * @Description 获取客户端IP地址
 * @Author      FengPQ
 * @DateTime    2020-05-14T17:25:41+0800
 * @param       integer                  $type [返回类型 0 返回IP地址 1 返回IPV4地址数字]
 * @param       boolean                  $adv  [是否进行高级模式获取（有可能被伪装）]
 * @return      [type]                         [description]
 */
function sys_get_client_ip($type = 0, $adv = false)
{
    $type      = $type ? 1 : 0;
    static $ip = null;
    if ($ip !== null) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }

            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * [sys_GetCurUrl php获取当前访问的完整url地址]
 * @Description php获取当前访问的完整url地址
 * @Author      FengPQ
 * @DateTime    2020-05-14T17:26:05+0800
 * @return      [type]                   [description]
 */
function sys_GetCurUrl()
{
    $url = 'http://';
    if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
        $url = 'https://';
    }
    if ($_SERVER['SERVER_PORT'] != '80') {
        $url .= $_SERVER['HTTP_HOST'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
    } else {
        $url .= $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }
    return $url;
}
?>